package io.renren.modules.practice.controller;

import io.renren.common.utils.R;
import io.renren.common.utils.ShiroUtils;
import io.renren.modules.practice.entity.AlgorithmQuizEntity;
import io.renren.modules.practice.entity.dto.AlgorithmSubmitDto;
import io.renren.modules.practice.entity.dto.CodeSaveDto;
import io.renren.modules.practice.entity.vo.AlgorithmQuizDetailVo;
import io.renren.modules.practice.entity.vo.AlgorithmSubmitResultVo;
import io.renren.modules.practice.service.AlgorithmPracticeService;
import io.renren.modules.learn.entity.AlgorithmChapterEntity;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@Slf4j
@RestController
@RequestMapping("/practice/algorithm")
public class AlgorithmPracticeController {

    @Autowired
    private AlgorithmPracticeService algorithmPracticeService;

    /**
     * 根据章节ID获取算法题目列表
     */
    @GetMapping("/chapter/{chapterId}/quizzes")
    public R getQuizListByChapterId(@PathVariable("chapterId") Integer chapterId) {
        try {
            List<AlgorithmQuizEntity> quizList = algorithmPracticeService.getQuizListByChapterId(chapterId);
            return R.ok().put("data", quizList);
        } catch (Exception e) {
            log.error("获取算法题目列表异常: {}", e.getMessage(), e);
            return R.error("获取题目列表失败");
        }
    }

    /**
     * 根据题目ID获取题目详情
     */
    @GetMapping("/quiz/{quizId}")
    public R getQuizDetailById(@PathVariable("quizId") Integer quizId) {
        try {
            AlgorithmQuizDetailVo quizDetail = algorithmPracticeService.getQuizDetailById(quizId);
            if (quizDetail == null) {
                return R.error("题目不存在");
            }
            return R.ok().put("data", quizDetail);
        } catch (Exception e) {
            log.error("获取算法题目详情异常: {}", e.getMessage(), e);
            return R.error("获取题目详情失败");
        }
    }

    /**
     * 提交算法题目代码
     */
    @PostMapping("/submit")
    public R submitAlgorithmCode(@RequestBody AlgorithmSubmitDto submitDto) {
        try {
            AlgorithmSubmitResultVo result = algorithmPracticeService.submitAlgorithmCode(submitDto);
            return R.ok().put("data", result);
        } catch (Exception e) {
            log.error("算法题目提交异常: {}", e.getMessage(), e);
            return R.error("提交失败: " + e.getMessage());
        }
    }

    /**
     * 保存用户代码
     */
    @PostMapping("/save-code")
    public R saveUserCode(@RequestBody CodeSaveDto codeSaveDto) {
        try {
            algorithmPracticeService.saveUserCode(codeSaveDto);
            return R.ok("代码保存成功");
        } catch (Exception e) {
            log.error("保存代码异常: {}", e.getMessage(), e);
            return R.error("保存失败: " + e.getMessage());
        }
    }

    /**
     * 获取用户保存的代码列表（兼容 /saved-codes?quizId=xxx）
     */
    @GetMapping("/saved-codes")
    public R getUserSavedCodesByParam(@RequestParam("quizId") Integer quizId) {
        try {
            Integer userId = ShiroUtils.getUserId().intValue();
            List<CodeSaveDto> savedCodes = algorithmPracticeService.getUserSavedCodes(userId, quizId);
            return R.ok().put("data", savedCodes);
        } catch (Exception e) {
            log.error("获取保存代码异常: {}", e.getMessage(), e);
            return R.error("获取保存代码失败");
        }
    }

    /**
     * 获取算法章节列表
     */
    @GetMapping("/chapters")
    public R getChapters() {
        try {
            List<AlgorithmChapterEntity> chapters = algorithmPracticeService.getChapters();
            return R.ok().put("data", chapters);
        } catch (Exception e) {
            log.error("获取章节列表异常: {}", e.getMessage(), e);
            return R.error("获取章节列表失败");
        }
    }

    /**
     * 按章节ID查询题目列表（支持前端/quiz/list接口）
     */
    @GetMapping("/quiz/list")
    public R getQuizListByChapterIdForList(@RequestParam("chapterId") Integer chapterId) {
        try {
            List<AlgorithmQuizEntity> quizList = algorithmPracticeService.getQuizListByChapterId(chapterId);
            return R.ok().put("data", quizList);
        } catch (Exception e) {
            log.error("获取算法题目列表异常: {}", e.getMessage(), e);
            return R.error("获取题目列表失败");
        }
    }

    /**
     * 运行Python代码，支持python2/python3
     */
    @PostMapping("/run")
    public R runPythonCode(@RequestBody AlgorithmSubmitDto submitDto) {
        try {
            String result = algorithmPracticeService.runPythonCode(submitDto.getCode(), submitDto.getPythonVersion());
            return R.ok().put("result", result);
        } catch (Exception e) {
            log.error("运行Python代码异常: {}", e.getMessage(), e);
            return R.error("运行失败: " + e.getMessage());
        }
    }
} 